package com.example.sprintboot.controller;

import com.example.sprintboot.common.Result;
import com.example.sprintboot.entity.Nutriment;
import com.example.sprintboot.service.NutrimentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 营养成分控制器
 */
@RestController
@RequestMapping("/nutriment")
@Tag(name = "营养成分管理", description = "营养成分相关接口")
public class NutrimentController {

    @Autowired
    private NutrimentService nutrimentService;

    /**
     * 根据ID查询营养成分
     */
    @Operation(summary = "根据ID查询营养成分", description = "通过营养成分ID获取详细信息")
    @GetMapping("/{id}")
    public Result getById(@Parameter(description = "营养成分ID") @PathVariable Integer id) {
        Nutriment nutriment = nutrimentService.getById(id);
        if (nutriment != null) {
            return Result.success(nutriment);
        } else {
            return Result.error("营养成分不存在");
        }
    }

    /**
     * 查询所有营养成分
     */
    @Operation(summary = "查询所有营养成分", description = "获取所有营养成分列表")
    @GetMapping("/all")
    public Result getAll() {
        List<Nutriment> list = nutrimentService.getAll();
        return Result.success(list);
    }

    /**
     * 查询公开的营养成分
     */
    @Operation(summary = "查询公开营养成分", description = "获取所有公开的营养成分列表")
    @GetMapping("/public")
    public Result getPublic() {
        List<Nutriment> list = nutrimentService.getPublicNutriments();
        return Result.success(list);
    }

    /**
     * 根据用户ID查询营养成分
     */
    @Operation(summary = "根据用户ID查询营养成分", description = "获取指定用户的营养成分列表")
    @GetMapping("/user/{userId}")
    public Result getByUserId(@Parameter(description = "用户ID") @PathVariable Integer userId) {
        List<Nutriment> list = nutrimentService.getByUserId(userId);
        return Result.success(list);
    }

    /**
     * 根据名称搜索营养成分
     */
    @Operation(summary = "搜索营养成分", description = "根据名称模糊搜索营养成分")
    @GetMapping("/search")
    public Result searchByName(@Parameter(description = "搜索关键字") @RequestParam String name) {
        List<Nutriment> list = nutrimentService.searchByName(name);
        return Result.success(list);
    }

    /**
     * 分页查询营养成分
     */
    @Operation(summary = "分页查询营养成分", description = "分页获取营养成分列表")
    @GetMapping("/page")
    public Result getByPage(
            @Parameter(description = "页码，从1开始") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) {
        
        List<Nutriment> list = nutrimentService.getByPage(page, size);
        int total = nutrimentService.count();
        
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        data.put("total", total);
        data.put("page", page);
        data.put("size", size);
        data.put("pages", (int) Math.ceil((double) total / size));
        
        return Result.success(data);
    }

    /**
     * 条件查询营养成分
     */
    @Operation(summary = "条件查询营养成分", description = "根据多个条件查询营养成分")
    @GetMapping("/condition")
    public Result searchByCondition(
            @Parameter(description = "用户ID") @RequestParam(required = false) Integer userId,
            @Parameter(description = "名称关键字") @RequestParam(required = false) String name,
            @Parameter(description = "是否公开") @RequestParam(required = false) String isPublic,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size) {
        
        List<Nutriment> list = nutrimentService.searchByCondition(userId, name, isPublic, page, size);
        int total = nutrimentService.countByCondition(userId, name, isPublic);
        
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        data.put("total", total);
        data.put("page", page);
        data.put("size", size);
        data.put("pages", (int) Math.ceil((double) total / size));
        
        return Result.success(data);
    }

    /**
     * 添加营养成分
     */
    @Operation(summary = "添加营养成分", description = "创建新的营养成分")
    @PostMapping
    public Result add(@RequestBody Nutriment nutriment) {
        // 基本验证
        if (nutriment.getName() == null || nutriment.getName().trim().isEmpty()) {
            return Result.error("营养成分名称不能为空");
        }
        
        // 检查名称是否已存在
        if (nutrimentService.existsByName(nutriment.getName(), nutriment.getUserId())) {
            return Result.error("营养成分名称已存在");
        }
        
        boolean success = nutrimentService.add(nutriment);
        if (success) {
            return Result.success(nutriment, "添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    /**
     * 更新营养成分
     */
    @Operation(summary = "更新营养成分", description = "更新营养成分信息")
    @PutMapping("/{id}")
    public Result update(@Parameter(description = "营养成分ID") @PathVariable Integer id, 
                        @RequestBody Nutriment nutriment) {
        nutriment.setId(id);
        
        // 检查营养成分是否存在
        Nutriment existing = nutrimentService.getById(id);
        if (existing == null) {
            return Result.error("营养成分不存在");
        }
        
        boolean success = nutrimentService.update(nutriment);
        if (success) {
            return Result.success(nutriment, "更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 删除营养成分
     */
    @Operation(summary = "删除营养成分", description = "根据ID删除营养成分")
    @DeleteMapping("/{id}")
    public Result delete(@Parameter(description = "营养成分ID") @PathVariable Integer id) {
        boolean success = nutrimentService.deleteById(id);
        if (success) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 批量删除营养成分
     */
    @Operation(summary = "批量删除营养成分", description = "根据ID列表批量删除营养成分")
    @DeleteMapping("/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的营养成分");
        }
        
        int count = nutrimentService.batchDelete(ids);
        return Result.success("成功删除 " + count + " 个营养成分");
    }

    /**
     * 切换公开状态
     */
    @Operation(summary = "切换公开状态", description = "切换营养成分的公开/私有状态")
    @PutMapping("/{id}/toggle-public")
    public Result togglePublicStatus(@Parameter(description = "营养成分ID") @PathVariable Integer id) {
        boolean success = nutrimentService.togglePublicStatus(id);
        if (success) {
            return Result.success("状态切换成功");
        } else {
            return Result.error("状态切换失败");
        }
    }

    /**
     * 统计信息
     */
    @Operation(summary = "获取统计信息", description = "获取营养成分的统计信息")
    @GetMapping("/statistics")
    public Result getStatistics(@Parameter(description = "用户ID") @RequestParam(required = false) Integer userId) {
        Map<String, Object> stats = new HashMap<>();
        
        if (userId != null) {
            // 用户统计
            stats.put("userTotal", nutrimentService.countByUserId(userId));
            stats.put("userPublic", nutrimentService.countByCondition(userId, null, "Y"));
            stats.put("userPrivate", nutrimentService.countByCondition(userId, null, "N"));
        }
        
        // 全局统计
        stats.put("total", nutrimentService.count());
        stats.put("publicTotal", nutrimentService.countByCondition(null, null, "Y"));
        stats.put("privateTotal", nutrimentService.countByCondition(null, null, "N"));
        
        return Result.success(stats);
    }
}